package com.example.demo.service;

import com.example.demo.domain.StudentInfo;
import com.example.demo.mapper.StudentInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import java.util.List;

@Service
public class StudentInfoServiceImpl implements StudentInfoService {
    @Autowired
    StudentInfoMapper studentInfoMapper;
    // 编程式事务
    @Autowired
    private DataSourceTransactionManager transactionManager; // 事务管理器

    @Autowired
    private TransactionDefinition transactionDefinition; // 定义事务属性



    @Override
    public List<StudentInfo> getAllStudent() {
        TransactionStatus transactionStatus = null;
        List<StudentInfo> studentInfos= null;
        try {

            // 1. 开启事务
            // 传入 transactionDefinition 给事务管理器 transactionManager 创建一个 transactionStatus 事务
            transactionStatus = transactionManager.getTransaction(transactionDefinition);

            studentInfos = studentInfoMapper.selectList(null);

            // 2. 事务提交
            transactionManager.commit(transactionStatus);

        } catch (Exception e) {
            // 事务对象yi常
            if (transactionStatus != null) {
                transactionManager.rollback(transactionStatus); // 事务回滚
            }
            return null;
        }


        return studentInfos;
    }
}
